﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using SW.Lite.IDAL.Master;
using SW.Lite.Infrastructure.Common;
using SW.Lite.Infrastructure.Helpers;
using SW.Lite.Model.Master;

namespace SW.Lite.DAL.MsSql.Master
{
    public class Button : IButton
    {
        public bool Exists(int id)
        {
            const string sql = "SELECT COUNT(1) FROM SW_M_Button WHERE Id=@Id";
            var paramter = new SqlParameter("@Id", SqlDbType.Int) { Value = id };
            return MsSqlHelper.Exists(sql, paramter);
        }

        public ButtonModel Single(int id)
        {
            const string sql = "SELECT Id, MenuID, Code, Title, Icon, Attributes, Sort FROM SW_M_Button WHERE Id=@Id";

            var paramter = new SqlParameter("@Id", SqlDbType.Int) { Value = id };
            return FillSingle(sql, paramter);
        }

        public PageList<ButtonModel> All()
        {
            const string sql = "SELECT Id, MenuID, Code, Title, Icon, Attributes, Sort FROM SW_M_Button";

            return FillList(sql);
        }

        public PageList<ButtonModel> All(int menuId, int pageIndex, int pageSize)
        {
            var start = (pageIndex - 1) * pageSize;
            var end = pageIndex * pageSize;
            var sql = string.Format(@"SELECT Id, MenuID, Code, Title, Icon, Attributes, Sort FROM (SELECT ROW_NUMBER() OVER (ORDER BY Id) ROWNO,* FROM SW_M_Button WHERE MenuID={2}) A WHERE A.ROWNO BETWEEN {0} AND {1};
            SELECT COUNT(1) FROM SW_M_Button WHERE MenuID={2};", start, end, menuId);
            return FillList(sql);
        }

        public ExecuteResult Insert(ButtonModel model)
        {
            const string sql = "INSERT INTO SW_M_Button(MenuID, Code, Title, Icon, Attributes, Sort) VALUES (@MenuID, @Code, @Title, @Icon, @Attributes, @Sort)";

            var parameters = new[]
            {
                new SqlParameter("@MenuID", SqlDbType.Int) {Value = model.MenuID},
                new SqlParameter("@Code", SqlDbType.NVarChar) {Value = model.Code},
                new SqlParameter("@Title", SqlDbType.NVarChar) {Value = model.Title},
                new SqlParameter("@Icon", SqlDbType.NVarChar) {Value = model.Icon},
                new SqlParameter("@Attributes", SqlDbType.NVarChar) {Value = model.Attributes},
                new SqlParameter("@Sort", SqlDbType.Int) {Value = model.Sort}
            };

            var result = MsSqlHelper.Execute(sql, parameters);
            return 0 == result ? new ExecuteResult(false) : new ExecuteResult(true);
        }

        public ExecuteResult Update(ButtonModel model)
        {
            const string sql = "UPDATE SW_M_Button SET MenuID=@MenuID, Code=@Code, Title=@Title, Icon=@Icon, Attributes=@Attributes, Sort=@Sort WHERE Id=@Id ";
            var parameters = new[]
            {
                new SqlParameter("@Id", SqlDbType.Int) {Value = model.Id},
                new SqlParameter("@MenuID", SqlDbType.Int) {Value = model.MenuID},
                new SqlParameter("@Code", SqlDbType.NVarChar) {Value = model.Code},
                new SqlParameter("@Title", SqlDbType.NVarChar) {Value = model.Title},
                new SqlParameter("@Icon", SqlDbType.NVarChar) {Value = model.Icon},
                new SqlParameter("@Attributes", SqlDbType.NVarChar) {Value = model.Attributes},
                new SqlParameter("@Sort", SqlDbType.Int) {Value = model.Sort}
            };

            var result = MsSqlHelper.Execute(sql, parameters);
            return 0 == result ? new ExecuteResult(false) : new ExecuteResult(true);
        }

        public ExecuteResult Delete(int id)
        {
            const string sql = "DELETE FROM SW_M_Button WHERE Id=@Id";
            var paramter = new SqlParameter("@Id", SqlDbType.Int) { Value = id };
            var result = MsSqlHelper.Execute(sql, paramter);
            return 0 == result ? new ExecuteResult(false) : new ExecuteResult(true);
        }

        public PageList<ButtonModel> GetButtonsByRoleIds(params int[] roleIds)
        {
            if (roleIds == null || roleIds.Length <= 0)
                return new PageList<ButtonModel>();

            var ids = roleIds.Select(n => n.ToString());

            var sql = "SELECT Id, MenuID, Code, Title, Icon, Attributes, Sort FROM SW_M_Button WHERE Id IN(SELECT ButtonID FROM SW_M_ButtonRole WHERE RoleID IN ('" + String.Join("','", ids) + "'))";

            return FillList(sql);
        }

        public PageList<ButtonModel> GetButtonsByMenuId(int menuId)
        {
            var sql = "SELECT Id, MenuID, Code, Title, Icon, Attributes, Sort FROM SW_M_Button WHERE MenuID=" + menuId;

            return FillList(sql);
        }

        private ButtonModel FillSingle(string sql, params SqlParameter[] paramters)
        {
            ButtonModel data = null;
            using (var rdr = MsSqlHelper.ExecuteReader(sql, paramters))
            {
                if (rdr.Read())
                    data = ReadData(rdr);
            }
            return data;
        }

        private PageList<ButtonModel> FillList(string sql, params SqlParameter[] paramters)
        {
            var list = new PageList<ButtonModel>();
            using (var rdr = MsSqlHelper.ExecuteReader(sql, paramters))
            {
                while (rdr.Read())
                    list.Add(ReadData(rdr));
                if (rdr.NextResult() && rdr.Read())
                    list.AllCount = rdr.GetInt32(0);
                else
                    list.AllCount = list.Count;
            }
            return list;
        }

        private ButtonModel ReadData(SqlDataReader dr)
        {
            return new ButtonModel
            {
                Id = Convert.ToInt32(dr["Id"]),
                MenuID = Convert.ToInt32(dr["MenuID"]),
                Code = Convert.ToString(dr["Code"]),
                Title = Convert.ToString(dr["Title"]),
                Icon = Convert.ToString(dr["Icon"]),
                Attributes = Convert.ToString(dr["Attributes"]),
                Sort = Convert.ToInt32(dr["Sort"])
            };
        }
    }
}